// src/main/java/com/example/securitydemo/config/SecurityConfig.java
package com.itheima.springbootsecuritydemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // 配置安全过滤规则
    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers( "/css/**", "/js/**").permitAll()
                        .requestMatchers("/public/**").permitAll()  // 允许所有人访问
                        // 限制/user路径仅允许具有USER角色的用户访问
                        .requestMatchers("/user/**").hasRole("USER")
                        .requestMatchers("/admin/**").hasRole("ADMIN") // 需要ADMIN角色
                        .anyRequest().authenticated() // 其他请求需要登录
                )
                .formLogin(form -> form
                        // 自定义登录页跳转到指定html页面
                        .loginProcessingUrl("/login")// 登录地址
                        //  .loginPage("/login.html") // 自定义登录页地址
                        .defaultSuccessUrl("/home", true) // 登录成功跳转
                        .permitAll()
                )
                .logout(logout -> logout
                        .logoutUrl("/logout") // 退出登录地址
                        .logoutSuccessUrl("/login?logout") // 退出后跳转
                );
        return http.build();
    }

    // 临时内存用户（后续替换为数据库）
    @Bean
    UserDetailsService userDetailsService() {
        UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder().encode("123456"))
                .roles("USER")
                .build();

        UserDetails admin = User.builder()
                .username("admin")
                .password(passwordEncoder().encode("admin"))
                .roles("ADMIN")
                .build();

        return new InMemoryUserDetailsManager(user, admin);
    }

    // 密码加密器
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}